<template>
  <div class="app-container">
    <el-container>
      <el-header style="margin-top: 10px;height: auto;">
        <el-row>
          <el-col :span="4">
            <el-select v-model="searchForm.user_id" placeholder="选择业务员" clearable style="width: 100%">
              <el-option
                v-for="item in users"
                :key="item.id"
                :label="item.first_name + item.last_name"
                :value="item.id"
              />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 100%">
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.is_pass" placeholder="选择审核状态" clearable style="width: 100%">
              <el-option
                v-for="item in isPassOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-input
              v-model="searchForm.kw"
              placeholder="输入提成月份搜索"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">
                  <i class="el-icon-search" />
                </el-button>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" style="width: 100%" @click="openDialog">新增提成</el-button>
          </el-col>
        </el-row>
      </el-header>
      <el-main>
        <el-table
          v-loading="loading"
          :data="commissionList"
          border
          style="width: 100%"
        >
          <!--        <el-table-column label="ID" prop="id" width="80" />-->
          <el-table-column label="提成月份" prop="commission_month" width="120" />
          <el-table-column label="业务员" prop="user_name" width="120" />
          <el-table-column label="毛利" prop="commission_amount" width="120">
            <template slot-scope="scope">
              {{ scope.row.commission_amount || 0 }}
            </template>
          </el-table-column>
          <el-table-column label="梯度提成" prop="commission_details" width="120">
            <template slot-scope="scope">
              {{ scope.row.commission_details }}
            </template>
          </el-table-column>
          <el-table-column label="提成金额" prop="commission_value" width="120">
            <template slot-scope="scope">
              {{ scope.row.commission_value || 0 }}
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" width="180">
            <template slot-scope="scope">
              <el-select v-model="scope.row.status" @change="handleUpdateStatus(scope.row, 'status', scope.row.status)">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="审核状态" prop="is_pass" width="240">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.is_pass"
                active-text="通过"
                inactive-text="未通过"
                :disabled="!isFinanceManager"
                @change="handleUpdateStatus(scope.row, 'is_pass', scope.row.is_pass)"
              />
            </template>
          </el-table-column>
          <el-table-column label="关联订单" width="150">
            <template slot-scope="scope">
              <el-button type="text" @click="selectedOrderInfo = scope.row.orders; drawerVisible = true">查看订单</el-button>
              <span>{{ scope.row.orders ? scope.row.orders.length : 0 }}个订单</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="created_at" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="small"
                type="primary"
                @click="openEditDialog(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-if="total > 0"
          :current-page="page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 15px; text-align: right;"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>
    <!-- 新增提成对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      title="新增提成"
      width="50%"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="业务员" prop="user_id">
          <el-select v-model="form.user_id" placeholder="选择业务员" style="width: 100%">
            <el-option
              v-for="item in users"
              :key="item.id"
              :label="item.first_name + item.last_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="提成月份" prop="commission_month">
          <el-input v-model="form.commission_month" placeholder="格式: YYYY-MM" />
        </el-form-item>
        <el-form-item v-if="isFinanceManager" label="审核状态" prop="is_pass">
          <el-switch
            v-model="form.is_pass"
            active-text="通过"
            inactive-text="未通过"
          />
        </el-form-item>
        <el-form-item v-if="isFinanceUser" label="状态" prop="status">
          <el-select v-model="form.status" placeholder="选择状态" style="width: 100%">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关联订单" prop="crmorders_ids">
          <el-select
            v-model="form.crmorders_ids"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入订单号搜索"
            :remote-method="remoteSearchOrder"
            :loading="searchOrderLoading"
            style="width: 100%"
          >
            <el-option
              v-for="item in orderSearchResults"
              :key="item.id"
              :label="`${item.order_no} - ${item.name}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="formLoading" @click="submitForm($refs.formRef)">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 订单详情抽屉 -->
    <el-drawer
      :visible.sync="drawerVisible"
      title="关联订单信息"
      direction="rtl"
      size="60%"
    >
      <el-table :data="selectedOrderInfo" border style="width: 100%">
        <el-table-column label="订单号" prop="order_no" width="250">
          <template slot-scope="scope">
            <el-button type="text" @click="openOrderDetail(scope.row)">{{ scope.row.order_no }}</el-button>
            <br><span>{{ scope.row.name }}</span>
            <br><span>{{ scope.row.create_at }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="crmorderstate_name" width="120" />
        <el-table-column label="财务记录">
          <template slot-scope="scope">
            <el-table :data="scope.row.financial_records" border style="width: 100%">
              <el-table-column label="金额" prop="amount" width="120">
                <template slot-scope="row">
                  <span :style="{ color: row.row.is_income ? '#67C23A' : '#F56C6C' }">
                    {{ row.row.is_income ? row.row.amount : '-' + row.row.amount }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="类型" prop="transaction_type" width="120" />
              <!-- <el-table-column label="收入|支出" prop="is_income" width="120">
                <template slot-scope="row">
                  <span :style="{ color: row.row.is_income ? '#67C23A' : '#F56C6C' }">
                    {{ row.row.is_income ? '收入' : '支出' }}
                  </span>
                </template>
              </el-table-column> -->
              <el-table-column label="交易日期" prop="transaction_date" width="180" />
            </el-table>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <!-- 订单详情组件 -->
    <crmorderdetail
      :order_data="current_order"
      :show-able="modifyOrderStateVisible"
      :order-states="parentOrderStats"
      @close="modifyOrderStateVisible=false"
    />

    <!-- 编辑提成对话框 -->
    <el-dialog
      :visible.sync="editDialogVisible"
      title="编辑提成"
      width="50%"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="业务员" prop="user_id">
          <el-select v-model="editForm.user_id" placeholder="选择业务员" style="width: 100%">
            <el-option
              v-for="item in users"
              :key="item.id"
              :label="item.first_name + item.last_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="提成月份" prop="commission_month">
          <el-input v-model="editForm.commission_month" placeholder="格式: YYYY-MM" />
        </el-form-item>
        <el-form-item v-if="isFinanceManager" label="审核状态" prop="is_pass">
          <el-switch
            v-model="editForm.is_pass"
            active-text="通过"
            inactive-text="未通过"
          />
        </el-form-item>
        <el-form-item v-if="isFinanceUser" label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="选择状态" style="width: 100%">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关联订单" prop="crmorders_ids">
          <el-select
            v-model="editForm.crmorders_ids"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入订单号搜索"
            :remote-method="remoteSearchOrder"
            :loading="searchOrderLoading"
            style="width: 100%"
          >
            <el-option
              v-for="item in orderSearchResults"
              :key="item.id"
              :label="`${item.order_no} - ${item.name}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="formLoading" @click="submitEditForm($refs.editFormRef)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { Get, Post, Put, Delete } from '@/api/crm/crmordercommission'
import { Get as GetOrder } from '@/api/crm/crmorder'
import { Get as GetOrderStatus } from '@/api/crm/crmorderstate'
import { CRMGetProjectUsers as GetUsers } from '@/api/crm/crmmanage'
import qs from 'qs'
import Crmorderdetail from './elements/crmorderdetail'

export default {
  name: 'CRMOrderCommission',
  components: { Crmorderdetail },
  data() {
    return {
      searchForm: {
        user_id: '',
        status: '',
        is_pass: '',
        kw: ''
      },
      users: [],
      commissionList: [],
      loading: false,
      dialogVisible: false,
      formLoading: false,
      total: 0,
      page: 1,
      pagesize: 10,
      statusOptions: [
        { value: '未结算', label: '未结算' },
        { value: '已结算', label: '已结算' }
      ],
      isPassOptions: [
        { value: true, label: '已审核' },
        { value: false, label: '未审核' }
      ],
      form: {
        user_id: '',
        is_pass: false,
        status: '未结算',
        commission_month: '',
        crmorders_ids: []
      },
      searchOrderLoading: false,
      orderSearchResults: [],
      selectedOrderInfo: [],
      drawerVisible: false,
      modifyOrderStateVisible: false,
      current_order: {
        name: ''
      },
      rules: {
        user_id: [{ required: true, message: '请选择业务员', trigger: 'change' }],
        crmorders_ids: [{ required: true, message: '请关联至少一个订单', trigger: 'change' }]
      },
      editDialogVisible: false,
      editForm: {
        id: '',
        user_id: '',
        is_pass: false,
        status: '未结算',
        commission_month: '',
        crmorders_ids: []
      },
      orderStates: [],
      orderstatesloading: false,
      parentOrderStats: []
    }
  },
  computed: {
    isFinanceManager() {
      return this.$store.getters.roles.indexOf('finance_manager') !== -1
    },
    isFinanceUser() {
      return this.$store.getters.roles.indexOf('finance_user') !== -1
    }
  },
  mounted() {
    this.getUsers()
    this.getCommissionList()
    this.handleGetOrderState()
  },
  methods: {
    // 获取订单状态
    handleGetOrderState() {
      this.orderstatesloading = true
      GetOrderStatus(null, qs.stringify({
        pagesize: 500,
        all: '1',
        page: 1,
        order_by: 'index',
        order_desc: 0
      })).then(response => {
        this.orderStates = response.data.data.map(item => {
          item.children = item.childrens
          return item
        })
        // 获取 parent_id为空的所有状态
        this.parentOrderStats = this.orderStates.filter(item => !item.parent_id)
        this.orderstatesloading = false
      }).catch(err => {
        console.log(err)
        this.orderstatesloading = false
      })
    },
    // 获取用户列表
    async getUsers() {
      try {
        const { data } = await GetUsers()
        this.users = data.data
        console.log('获取用户列表成功', this.users)
      } catch (error) {
        console.error('获取用户列表失败', error)
      }
    },

    // 获取提成列表
    async getCommissionList() {
      this.loading = true
      try {
        const queryParams = {
          ...this.searchForm,
          page: this.page,
          pagesize: this.pagesize
        }

        const args = qs.stringify(queryParams)
        const { data } = await Get('', args)
        this.commissionList = data.data
        this.total = data.total
      } catch (error) {
        console.error('获取提成列表失败', error)
      } finally {
        this.loading = false
      }
    },

    // 远程搜索订单
    async remoteSearchOrder(query) {
      if (query.length < 2) return

      this.searchOrderLoading = true
      try {
        const args = qs.stringify({ kw: query })
        const { data } = await GetOrder('', args)
        this.orderSearchResults = data.data || []
      } catch (error) {
        console.error('搜索订单失败', error)
      } finally {
        this.searchOrderLoading = false
      }
    },

    // 提交表单
    async submitForm(formEl) {
      if (!formEl) return

      formEl.validate(async(valid) => {
        if (valid) {
          this.formLoading = true
          try {
            // 如果是当月，自动设置提成月份
            if (!this.form.commission_month) {
              const now = new Date()
              this.form.commission_month = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
            }

            await Post(this.form)
            this.notify('新增提成记录成功')
            this.dialogVisible = false
            this.getCommissionList()
            this.resetForm(formEl)
          } catch (error) {
            console.error('提交失败', error)
            this.$message.error('提交失败：' + error.message)
          } finally {
            this.formLoading = false
          }
        }
      })
    },

    // 删除提成记录
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除此提成记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await Delete(row.id)
        this.notify('删除成功')
        this.getCommissionList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败', error)
          this.$message.error('删除失败：' + error.message)
        }
      }
    },

    // 更改审核状态
    async handleUpdateStatus(row, field, value) {
      try {
        await Put(row.id, { [field]: value })
        this.notify('更新成功')
        this.getCommissionList()
      } catch (error) {
        console.error('更新失败', error)
        this.$message.error('更新失败：' + error.message)
      }
    },

    // 重置表单
    resetForm(formEl) {
      if (formEl) {
        formEl.resetFields()
      }
      this.form = {
        user_id: '',
        is_pass: false,
        status: '未结算',
        commission_month: '',
        crmorders_ids: []
      }
      this.orderSearchResults = []
      this.selectedOrderInfo = []
    },

    // 处理页码变化
    handlePageChange(val) {
      this.page = val
      this.getCommissionList()
    },

    // 处理每页条数变化
    handleSizeChange(val) {
      this.pagesize = val
      this.page = 1
      this.getCommissionList()
    },

    // 处理搜索
    handleSearch() {
      this.page = 1
      this.getCommissionList()
    },

    // 打开新增对话框
    openDialog() {
      this.dialogVisible = true
      // 设置当前月份为默认值
      const now = new Date()
      this.form.commission_month = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
    },

    // 消息通知
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },

    // 打开订单详情
    openOrderDetail(row) {
      this.modifyOrderStateVisible = true
      this.current_order = row
    },

    // 打开编辑对话框
    openEditDialog(row) {
      this.editDialogVisible = true
      this.editForm = {
        id: row.id,
        user_id: row.user_id,
        is_pass: row.is_pass,
        status: row.status,
        commission_month: row.commission_month,
        crmorders_ids: row.orders ? row.orders.map(order => order.id) : []
      }
      // 预加载已关联的订单
      this.orderSearchResults = row.orders || []
    },

    // 提交编辑表单
    async submitEditForm(formEl) {
      if (!formEl) return

      formEl.validate(async(valid) => {
        if (valid) {
          this.formLoading = true
          try {
            await Put(this.editForm.id, this.editForm)
            this.notify('修改提成记录成功')
            this.editDialogVisible = false
            this.getCommissionList()
            this.resetEditForm(formEl)
          } catch (error) {
            console.error('提交失败', error)
            this.$message.error('提交失败：' + error.message)
          } finally {
            this.formLoading = false
          }
        }
      })
    },

    // 重置编辑表单
    resetEditForm(formEl) {
      if (formEl) {
        formEl.resetFields()
      }
      this.editForm = {
        id: '',
        user_id: '',
        is_pass: false,
        status: '未结算',
        commission_month: '',
        crmorders_ids: []
      }
      this.orderSearchResults = []
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.el-header {
  padding: 0;
  margin-bottom: 20px;
}
.el-main {
  padding: 0;
}
.el-row {
  margin-bottom: 20px;
}
.el-col {
  padding: 0 10px;
}

/* 订单详情抽屉样式优化 */
.el-drawer >>> .el-drawer__body {
  padding: 0;
}

/* 抽屉内表格样式优化 */
.el-drawer >>> .el-table {
  margin-bottom: 20px;
}

/* 嵌套表格样式 */
.el-drawer >>> .el-table .el-table {
  margin-bottom: 0;
  border: none;
}

/* 嵌套表格行高调整 */
.el-drawer >>> .el-table .el-table .el-table__row {
  background-color: #f8f9fa;
}

/* 订单号列样式 */
.el-drawer >>> .el-table__body-wrapper {
  max-height: none;
}

/* 财务记录表格容器 */
.el-drawer >>> .el-table .el-table__body-wrapper {
  max-height: 200px;
  overflow-y: auto;
}

/* 优化按钮样式 */
.el-drawer >>> .el-button--text {
  padding: 0;
  color: #409EFF;
  font-weight: 500;
}

/* 订单信息显示优化 */
.el-drawer >>> .el-table-column span {
  display: inline-block;
  line-height: 1.5;
}

/* 状态列样式 */
.el-drawer >>> .el-table-column[label="状态"] {
  text-align: center;
}

/* 金额显示样式 */
.el-drawer >>> .el-table-column[label="金额"] {
  text-align: right;
}
</style>
